<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>1_引出生命周期</title>
</head>

<body>
<div id="test"></div>

<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<script type="text/javascript" src="../js/babel.min.js"></script>

<script type="text/babel">

    class Life extends React.Component {
        state = {opacity: 0.5}

        death = () => {
            console.log("death");
            //卸载组件
            ReactDOM.unmountComponentAtNode(document.getElementById('test'))
        }

        //初始化渲染、状态更新之后
        render() {
            console.log("render");
            return (
                <div>
                    <h2 style={{opacity: this.state.opacity}}>学不会react怎么办？</h2>
                    <button onClick={this.death}>不活了</button>
                </div>
            )
        }

        //组件挂载完毕
        componentDidMount() {
            console.log("componentDidMount")
            this.timer = setInterval(() => {
                //获取原状态
                let {opacity} = this.state;
                //减小o.1
                opacity -= 0.1;
                if (opacity <= 0) opacity = 1
                //设置新的透明度
                this.setState({opacity});
            }, 200);
        }

        //组件将要卸载
        componentWillUnmount() {
            //清除定时器
            clearInterval(this.timer)
        }
    }

    //渲染组件
    ReactDOM.render(<Life/>, document.getElementById('test'))

</script>
</body>

</html>
